package com.itheima.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.RouteDao;
import com.itheima.domain.Route;
import com.itheima.service.RouteService;
import com.itheima.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class RouteServiceImpl implements RouteService {


    @Override
    public void save(Route route) {
        //获得sqlSession 对象
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        //生成代理对象
        RouteDao routeDao = sqlSession.getMapper(RouteDao.class);

        //逻辑操作
        routeDao.save(route);


        //释放资源
        MyBatisUtils.commitAndClose(sqlSession);
    }

    @Override
    public void update(Route route) {
        //获得sqlSession 对象
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        //生成代理对象
        RouteDao routeDao = sqlSession.getMapper(RouteDao.class);

        //逻辑操作
        routeDao.update(route);

        //释放资源
        MyBatisUtils.commitAndClose(sqlSession);
    }

    @Override
    public void delete(Integer rid) {
//获得sqlSession 对象
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        //生成代理对象
        RouteDao routeDao = sqlSession.getMapper(RouteDao.class);

        //调用dao删除数据
        routeDao.delete(rid);


        //释放资源
        MyBatisUtils.commitAndClose(sqlSession);
    }

    @Override
    public PageInfo<Route> findAll(int pageNumber , int pageSize , Integer cid) {
        //获得sqlSession 对象
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        //生成代理对象
        RouteDao routeDao = sqlSession.getMapper(RouteDao.class);

        //开始进行mybatis分页
        PageHelper.startPage(pageNumber , pageSize);
        //逻辑操作
        List<Route> routeList = routeDao.findAll(cid);//分页数据

        //参数2: 页码数
        PageInfo<Route> pageInfo = new PageInfo<>(routeList, 10);


        //释放资源
        MyBatisUtils.commitAndClose(sqlSession);
        return pageInfo;
    }

    @Override
    public Route findById(Integer rid) {
        //获得sqlSession 对象
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        //生成代理对象
        RouteDao routeDao = sqlSession.getMapper(RouteDao.class);

        //逻辑操作
        Route route = routeDao.findById(rid);

        //释放资源
        MyBatisUtils.commitAndClose(sqlSession);
        return route;
    }




    public List<Route> template() {
        //获得sqlSession 对象
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        //生成代理对象
        RouteDao routeDao = sqlSession.getMapper(RouteDao.class);

        //逻辑操作


        //释放资源
        MyBatisUtils.commitAndClose(sqlSession);
        return null;
    }

}
